package training_camp.day1.leetcode34;

class Solution {
    /**
     * 第一个大于等于target的地方
     *
     * @param nums
     * @param target
     * @return
     */
    private int findLeftIndex(int[] nums, int target) {
        int n = nums.length;
        int l = 0;
        int r = n - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] > target) {
                r = mid - 1;
            } else if (nums[mid] < target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return r + 1;
    }

    /**
     * 最后一个小于等于target的地方
     *
     * @param nums
     * @param target
     * @return
     */
    private int findRightIndex(int[] nums, int target) {
        int n = nums.length;
        int l = 0;
        int r = n - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] > target) {
                r = mid - 1;
            } else if (nums[mid] < target) {
                l = mid + 1;
            } else {
                l = mid + 1;
            }
        }
        return l - 1;
    }

    public int[] searchRange(int[] nums, int target) {
        int begin = findLeftIndex(nums, target);
        if (begin >= nums.length || nums[begin]!=target){
            return new int[] {-1,-1};
        }
        int end  =  findRightIndex(nums, target);
        return new int[]{begin , end};
    }
}